package pbmsg

import (
	"fmt"
	"lnzw/common/proto/cs_gen"
	"lnzw/engine/encrypt"

	"google.golang.org/protobuf/proto"
)

var msgs = map[uint32]func() (req proto.Message, rsp proto.Message){}
var rsnot proto.Message

func register(reqname string, rspname string, msgnew func() (req proto.Message, rsp proto.Message)) {
	name := fmt.Sprintf("%s.%s", reqname, rspname)
	h := encrypt.Hash32(name)
	if _, ok := msgs[h]; ok {
		panic("duplicate msg")
	}
	msgs[h] = msgnew
}

func InitMsg() {
	rsnot = &cs_gen.ResNot{}
	register("ReqCreateMap", "ResCreateMap", func() (req proto.Message, rsp proto.Message) { return &cs_gen.ReqCreateMap{}, &cs_gen.ResCreateMap{} })
	register("ReqMapInfo", "ResMapInfo", func() (req proto.Message, rsp proto.Message) { return &cs_gen.ReqMapInfo{}, &cs_gen.ResMapInfo{} })
	register("ReqMapList", "ResMapList", func() (req proto.Message, rsp proto.Message) { return &cs_gen.ReqMapList{}, &cs_gen.ResMapList{} })
	register("ReqLogin", "ResLogin", func() (req proto.Message, rsp proto.Message) { return &cs_gen.ReqLogin{}, &cs_gen.ResLogin{} })
	register("ReqMapUnitInfo", "ResMapUnitInfo", func() (req proto.Message, rsp proto.Message) {
		return &cs_gen.ReqMapUnitInfo{}, &cs_gen.ResMapUnitInfo{}
	})
}

func GetMsg(h uint32) (req proto.Message, rsp proto.Message) {
	f := msgs[h]
	if f == nil {
		return nil, nil
	}
	return f()
}

func GetDefaultResNot() proto.Message {
	return rsnot
}
